package org.example.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.order.entity.Comment;
import org.example.order.mapper.CommentMapper;
import org.example.order.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public void add(Comment comment) {
        if (comment.getLikeCount() == null) {
            comment.setLikeCount(0);
        }
        baseMapper.insert(comment);
    }

    @Override
    public void deleteById(Long id) {
        baseMapper.deleteById(id);
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        for (Long id : ids) {
            baseMapper.deleteById(id);
        }
    }

    @Override
    public void update(Comment comment) {
        baseMapper.updateById(comment);
    }

    @Override
    public Comment selectById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public List<Comment> selectAll() {
        return baseMapper.selectList(null);
    }


    @Override
    public PageInfo<Comment> selectPage(Comment comment, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        // 使用 QueryWrapper 构建查询条件 (注意：这里应该是 Comment 而不是 Good)
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();

        // 如果 comment 不为 null，添加查询条件
        if (comment != null) {
            // 精确查询用户ID (userId 通常是 Long 类型，不需要模糊查询)
            if (comment.getUserId() != null) {
                wrapper.eq("user_id", comment.getUserId());
            }

            // 精确查询商品ID
            if (comment.getGoodId() != null) {
                wrapper.eq("good_id", comment.getGoodId());
            }

            // 如果需要根据评论内容模糊查询
            if (comment.getContent() != null && !comment.getContent().trim().isEmpty()) {
                wrapper.like("content", comment.getContent());
            }
        }

        // 使用 MyBatis-Plus 的方法查询，或者使用你的自定义方法
        // 方式1：使用 MyBatis-Plus
        List<Comment> list = commentMapper.selectList(wrapper);

        // 方式2：如果你有自定义的 mapper 方法，需要传递正确的参数
        // List<Comment> list = commentMapper.selectWithTitle(comment);

        return new PageInfo<>(list);
    }

    @Override
    public List<Comment> selectByUserIdOrGoodIdOrGoodName(Map<String, Object> params) {
        return commentMapper.selectByUserIdOrGoodIdOrGoodName(params);
    }
}